package com.zzjx.config;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
import java.util.concurrent.Executor;

@Slf4j
@Component
public class SysConfig implements EnvironmentAware {

    private static final String JPAAS_CONFIG = "nacos-config.properties";
    private static final String DEFAULT_GROUP = "DEFAULT_GROUP";

    private Properties properties = new Properties();

    //通过注入nacos config来获取配置文件json
    @NacosInjected
    private ConfigService configService;


    public String getVal(String key) throws NacosException, IOException {
        if (properties.size() == 0) {
            String config = configService.getConfig(JPAAS_CONFIG, DEFAULT_GROUP, 0L);
            StringReader reader = new StringReader(config);
            properties.load(reader);
        }
        return properties.getProperty("props." + key);
    }


    @Override
    public void setEnvironment(Environment environment) {
        try {
            //Nacos 服务提供接口 listener 用于客户端注册监听服务（基于web 容器的长连接技术）
            configService.addListener(JPAAS_CONFIG, DEFAULT_GROUP, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }
                //receiveConfigInfo从监听器中回调或者config
                @Override
                public void receiveConfigInfo(String config) {
                    try {
                        StringReader reader = new StringReader(config);
                        properties.load(reader);
                        log.debug("nacos properties reload");
                    } catch (Exception ex) {
                        log.error("receiveConfigInfo", ex);
                    }
                }
            });
        } catch (Exception ex) {
            log.error("setEnvironment", ex);
        }

    }
}
